<?php

declare(strict_types=1);

namespace App\Controller\Admin\User;

use App\Entity\AdminUser;
use App\Entity\AdminUserGroup;
use App\Utils\Annotation\ApiAuthority;
use App\Utils\Annotation\ApiName;
use App\Utils\Annotation\ApiParam;
use App\Utils\Helper\GeneralHelper;
use App\Utils\Traits\ControllerTrait;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

/**
 * Class AdminUserController
 * @package App\Controller\Admin\User
 * @Route("/admin/user/admin-user", name="admin-user-admin_user-")
 * @ApiName(name="用户")
 */
class AdminUserController extends AbstractController {
    use ControllerTrait;

    /**
     * @ApiName(name="获取指定用户信息")
     * @ApiParam(name="id", type="integer", comment="用户ID", require=true)
     * @ApiAuthority(need="admin.user.admin_user")
     * @Route("/info", methods={"GET"}, name="info")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     * @throws \Exception
     */
    public function info (Request $request) {
        $params = $this->onlyDeclare($request);
        $admin_user = $this->getDoctrine()->getRepository(AdminUser::class)->getInfoById($params['id']);
        if ($admin_user) {
            // 头像处理
            if (isset($admin_user['avatar'])) {
                $admin_user['avatar'] = GeneralHelper::getAvatar($admin_user['avatar']);
            }
            return json_success($admin_user);
        } else {
            return json_failure('用户不存在');
        }
    }

    /**
     * @ApiName(name="用户新建")
     * @ApiParam(name="username", type="string", comment="账号", require=true)
     * @ApiParam(name="email", type="string", comment="email", validation="email:true")
     * @ApiParam(name="password", type="string", comment="密码", validation="password:true", require=true)
     * @ApiParam(name="admin_user_group_id", type="integer", comment="用户组", require=true)
     * @ApiParam(name="nickname", type="string", comment="昵称")
     * @ApiParam(name="contact", type="string", comment="联系方式-手机号", validation="phone:true")
     * @ApiAuthority(need="admin.user.admin_user")
     * @Route("/create", methods={"POST"}, name="create")
     * @param Request $request
     * @param UserPasswordEncoderInterface $passwordEncoder
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     * @throws \Exception
     */
    public function create (Request $request, UserPasswordEncoderInterface $passwordEncoder) {
        $params = $this->onlyDeclare($request);
        $admin_user_username = $this->getDoctrine()->getRepository(AdminUser::class)->findOneBy(['username' => $params['username']]);
        if ($admin_user_username) {
            return json_failure('账号"'.$params['username'].'"已经存在');
        }
        if (isset($params['email']) && !empty($params['email'])) {
            $admin_user_email = $this->getDoctrine()->getRepository(AdminUser::class)->findOneBy(['email' => $params['email']]);
            if ($admin_user_email) {
                return json_failure('邮箱"'.$params['email'].'"已经存在');
            }
        }
        if (isset($params['contact']) && !empty($params['contact'])) {
            $admin_user_contact = $this->getDoctrine()->getRepository(AdminUser::class)->findOneBy(['contact' => $params['contact']]);
            if ($admin_user_contact) {
                return json_failure('联系方式"'.$params['contact'].'"已经存在');
            }
        }
        $admin_user = new AdminUser();
        $admin_user->setUsername($params['username']);
        $admin_user->setAdminUserGroupId($params['admin_user_group_id']);
        $admin_user->setPassword($passwordEncoder->encodePassword($admin_user, $params['password']));
        $admin_user->setNickname($params['nickname'] ?? '');
        $admin_user->setEmail($params['email'] ?? '');
        $admin_user->setContact($params['contact'] ?? '');
        $this->getDoctrine()->getManager()->persist($admin_user);
        $this->getDoctrine()->getManager()->flush();
        return json_success();
    }

    /**
     * @ApiName(name="用户更新")
     * @ApiParam(name="id", type="integer", comment="用户ID", require=true)
     * @ApiParam(name="username", type="string", comment="用户名", require=true)
     * @ApiParam(name="email", type="string", comment="email", validation="email:true")
     * @ApiParam(name="password", type="string", comment="密码", validation="password:true")
     * @ApiParam(name="admin_user_group_id", type="integer", comment="用户组", require=true)
     * @ApiParam(name="nickname", type="string", comment="昵称")
     * @ApiParam(name="contact", type="string", comment="联系方式-手机号", validation="phone:true")
     * @ApiAuthority(need="admin.user.admin_user")
     * @Route("/update", methods={"POST"}, name="update")
     * @param Request $request
     * @param UserPasswordEncoderInterface $passwordEncoder
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     * @throws \Exception
     */
    public function update (Request $request, UserPasswordEncoderInterface $passwordEncoder) {
        $params = $this->onlyDeclare($request);
        $admin_user = $this->getDoctrine()->getRepository(AdminUser::class)->find($params['id']);
        if (!$admin_user) {
            return json_failure('用户不存在');
        }
        $admin_user_username = $this->getDoctrine()->getRepository(AdminUser::class)->findOneByFieldAndNotId('username', $params['username'], $params['id']);
        if ($admin_user_username) {
            return json_failure('账号"'.$params['username'].'"已经存在');
        }
        if (isset($params['email']) && !empty($params['email'])) {
            $admin_user_email = $this->getDoctrine()->getRepository(AdminUser::class)->findOneByFieldAndNotId('email', $params['email'], $params['id']);
            if ($admin_user_email) {
                return json_failure('邮箱"'.$params['email'].'"已经存在');
            }
        }
        if (isset($params['contact']) && !empty($params['contact'])) {
            $admin_user_contact = $this->getDoctrine()->getRepository(AdminUser::class)->findOneByFieldAndNotId('contact', $params['contact'], $params['id']);
            if ($admin_user_contact) {
                return json_failure('联系方式"'.$params['contact'].'"已经存在');
            }
        }
        try {
            $admin_user->setUsername($params['username']);
            $admin_user->setAdminUserGroupId($params['admin_user_group_id']);
            $admin_user->setNickname($params['nickname'] ?? '');
            $admin_user->setEmail($params['email'] ?? '');
            $admin_user->setContact($params['contact'] ?? '');
            if (isset($params['password'])) {
                $admin_user->setPassword($passwordEncoder->encodePassword($admin_user, $params['password']));
            }
            $this->getDoctrine()->getManager()->persist($admin_user);
            $this->getDoctrine()->getManager()->flush();
            return json_success();
        } catch (\Exception $e) {
            return json_failure($e->getMessage());
        }
    }

    /**
     * @ApiName(name="获取用户列表")
     * @ApiParam(name="username", type="string", comment="用户名")
     * @ApiParam(name="nickname", type="string", comment="昵称")
     * @ApiParam(name="email", type="string", comment="email")
     * @ApiParam(name="admin_user_group_id", type="integer", comment="用户组ID")
     * @ApiParam(name="created_at", type="string", comment="创建日期")
     * @ApiParam(name="page", type="integer", comment="页码数", default="1")
     * @ApiParam(name="limit", type="integer", comment="每页条数", default="10")
     * @ApiAuthority(need="admin.user.admin_user")
     * @Route("/list", methods={"GET"}, name="list")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     * @throws \Exception
     */
    public function list (Request $request) {
        $params = $this->onlyDeclare($request);
        $admin_user_data = $this->getDoctrine()->getRepository(AdminUser::class)->search($params);
        $admin_user_total = $this->getDoctrine()->getRepository(AdminUser::class)->searchTotal($params);
        $admin_user_groups = $this->getDoctrine()->getRepository(AdminUserGroup::class)->getItems();
        foreach ($admin_user_data as &$admin_user) {
            $admin_user['admin_user_group'] = $admin_user_groups[$admin_user['admin_user_group_id']] ?? '-';
            $admin_user['created_at'] = $admin_user['created_at']->format('Y-m-d H:i:s');
            $admin_user['avatar'] = GeneralHelper::getAvatar($admin_user['avatar']);
        }
        return json_success([
            'data'  => $admin_user_data,
            'total' => $admin_user_total,
        ]);
    }

    /**
     * @ApiName(name="用户删除")
     * @ApiParam(name="id", type="integer", comment="用户ID", require=true)
     * @ApiAuthority(need="admin.user.admin_user")
     * @Route("/delete", methods={"POST"}, name="delete")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     * @throws \Exception
     */
    public function delete (Request $request) {
        $params = $this->onlyDeclare($request);
        $admin_user = $this->getDoctrine()->getRepository(AdminUser::class)->find($params['id']);
        if (!$admin_user) {
            return json_failure('用户不存在');
        }
        if ($admin_user->isSuperAdmin()) {
            return json_failure('超级管理员不能手动删除，请联系系统管理员');
        }
        $this->getDoctrine()->getManager()->remove($admin_user);
        $this->getDoctrine()->getManager()->flush();
        return json_success();
    }
}